<script setup>
import { RouterView, useRoute } from "vue-router";
import {
  NConfigProvider,
  NDialogProvider,
  NMessageProvider,
  NLayout,
  NLayoutHeader,
  NLayoutContent,
  NLayoutFooter,
  NFlex,
} from "naive-ui";
import HeadView from "./components/HeadView.vue";
import LaySiderView from "./components/LaySiderView.vue";
import { ref, watch } from "vue";

// 创建路由对象
const route = useRoute();

// 定义用户名变量，默认为admin
const username = ref(localStorage.getItem("username") || "admin");

// 监听路由变化，当从登录页跳转到其他页面时，更新username
watch(
  () => route.path,
  (newPath, oldPath) => {
    // 当从登录页跳转到其他页面或者刷新页面时，更新用户名
    if (oldPath === "/login" || newPath !== "/login") {
      username.value = localStorage.getItem("username") || "admin";
    }
  }
);
</script>

<template>
  <n-message-provider>
    <n-dialog-provider>
      <n-config-provider>
        <!-- 条件渲染：如果是登录页，只显示RouterView，否则显示完整布局 -->
        <template v-if="route.path === '/login'">
          <RouterView />
        </template>
        <template v-else>
          <div>
            <n-flex vertical class="content">
              <!-- 头部区域内容 -->
              <n-layout-header bordered class="header_content">
                <HeadView :username="username"></HeadView>
              </n-layout-header>
              <!-- 中间区域内容 -->
              <n-layout has-sider class="main_content">
                <!-- 侧边导航栏（使用拆分后的LaySiderView组件） -->
                <LaySiderView
                  :collapsed-width="64"
                  :width="240"
                  :collapsed-icon-size="22"
                />
                <!-- 侧边导航栏（使用拆分后的LaySiderView组件） -->

                <!-- 主体内容：条件渲染切换组件 -->
                <n-layout-content class="main_body">
                  <RouterView />
                </n-layout-content>
              </n-layout>
              <!-- 底部区域内容-->
              <n-layout-footer bordered class="footer_content">明电舍(杭州)电气系统有限公司 &copy;{{ new Date().getFullYear() }}</n-layout-footer>
            </n-flex>
          </div>
        </template>
      </n-config-provider>
    </n-dialog-provider>
  </n-message-provider>
</template>

<style scoped>
.content {
  height: 100vh;
  min-width: 100vh;
  display: flex;
  flex-direction: column;
}

.main_content {
  padding: 0px;
  flex: 1;
  overflow: hidden;
}

.header_content {
  height: 30px;
  padding: 0px;
}

.footer_content {
  height: 30px;
  text-align: center;
  padding: 0px;
}

.main_body {
  padding: 0px;
  overflow: auto;
}
</style>
